package com.deparse.dpframe.ui.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by MartinDKent on 2016/3/23.
 */
public abstract class DPBaseAdapter<T> extends BaseAdapter {
    private List<T> data;

    public DPBaseAdapter() {
    }

    public DPBaseAdapter(List<T> data) {
        this.data = data;
    }

    public void update(List<T> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return null == data ? 0 : data.size();
    }

    @Override
    public Object getItem(int position) {
        return null == data ? null : (position < data.size() ? data.get(position) : null);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CommonBaseViewHolder<T> holder;
        View view;

        if (null == convertView) {
            holder = getHolder(position);
            view = holder.create(position);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (CommonBaseViewHolder<T>) view.getTag();
        }
        holder.update(data.get(position));
        return view;
    }

    public abstract CommonBaseViewHolder<T> getHolder(int position);

    public static abstract class CommonBaseViewHolder<T> {

        public abstract View create(int position);

        public abstract void update(T data);
    }
}
